package com.ewhale.feitengguest.ui.shop.task

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.dto.*
import com.ewhale.feitengguest.presenter.shop.task.STaskDetailPresenter
import com.ewhale.feitengguest.ui.shop.release.ReleaseTaskActivity
import com.ewhale.feitengguest.ui.user.task.TaskDetailsActivity
import com.ewhale.feitengguest.ui.user.task.adapter.CommentAdapter
import com.ewhale.feitengguest.ui.user.task.adapter.StepListAdapter
import com.ewhale.feitengguest.utils.GlideImageLoader
import com.ewhale.feitengguest.view.shop.task.STaskDetailView
import com.ewhale.feitengguest.widget.HandlerDialog
import com.ewhale.feitengguest.widget.IncreaseNumberDialog
import com.ewhale.feitengguest.widget.IncreasePriceDialog
import com.ewhale.feitengguest.widget.ReplyDialog
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.simga.library.activity.MBaseActivity
import com.simga.library.utils.CheckUtil
import com.simga.library.utils.KeyBoardUtils
import com.simga.library.utils.glide.GlideUtil
import com.simga.library.widget.HintDialog
import kotlinx.android.synthetic.main.activity_shop_taskdetail.*
import kotlinx.android.synthetic.main.activity_shop_taskdetail.listview
import kotlinx.android.synthetic.main.activity_shop_taskdetail.ref_layout
import java.math.BigDecimal
import java.util.*

class STaskDetailActivity : MBaseActivity<STaskDetailPresenter>(), STaskDetailView {
    private var missionId: Long = 0
    private val mTabEntities = ArrayList<CustomTabEntity>()
    private var mStepAdapter: StepListAdapter? = null
    private var mCommentAdapter: CommentAdapter? = null
    private val stepList = ArrayList<TaskDetailsDto.MissionStepDtosBean>()
    private val imageUrl = ArrayList<String>()
    private val mCommentList = ArrayList<TaskCommentDto>()
    private var pageNum = 1
    private var openType = NORAL_OPEN
    private var mDetailsDto: ShopTaskDetailDto? = null
    private var handlerDialog: HandlerDialog? = null
    private var priceDialog: IncreasePriceDialog? = null
    private var numberDialog: IncreaseNumberDialog? = null
    private val myReceiver by lazy(LazyThreadSafetyMode.NONE) { MyReciver() }
    private val replyDialog by lazy(LazyThreadSafetyMode.NONE) { ReplyDialog(mContext) }

    override fun init(savedInstanceState: Bundle?) {
        val filter = IntentFilter()
        filter.addAction("UPDATE_TASK_DETAIL")
        registerReceiver(myReceiver, filter)
        mTabEntities.add(TabEntity("任务步骤", 0, 0))
        mTabEntities.add(TabEntity("留言", 0, 0))
        topMainTab.setTabData(mTabEntities)
        if (openType == NORAL_OPEN) {
            topMainTab.currentTab = 0
        } else {
            topMainTab.currentTab = 1
        }
        ref_layout.setEnableRefresh(false)
        ref_layout.setEnableLoadmore(false)
        bannerlayout.setImageLoader(GlideImageLoader())
        mCommentAdapter = CommentAdapter(mCommentList, CommentAdapter.SHOP_SIDE)
        mStepAdapter = StepListAdapter(stepList)
        listview.adapter = mStepAdapter
        listview.apply {
            adapter = if (openType == NORAL_OPEN) {
                mStepAdapter
            } else {
                mCommentAdapter
            }
            layoutManager = object : LinearLayoutManager(mContext, RecyclerView.VERTICAL, false) {
                override fun canScrollVertically() = false
            }
            isNestedScrollingEnabled = false
            setHasFixedSize(false)
            isFocusable = false
        }
        xloading_view.showContent()
        presenter.loadTaskDetail(missionId)
        presenter.loadComment(missionId, pageNum)
    }

    override fun initListener() {
        super.initListener()
        topMainTab.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                if (position == 0) {
                    xloading_view.showContent()
                    if (!CheckUtil.isNull(mDetailsDto!!.missionQrcode)) {
                        iv_taskQRCode.visibility = View.VISIBLE
                    }
                    if (!CheckUtil.isNull(mDetailsDto!!.missionUrl)) {
                        tv_linkText.visibility = View.VISIBLE
                    }
                    if (!CheckUtil.isNull(mDetailsDto!!.missionUrl) || !CheckUtil.isNull(mDetailsDto!!.missionQrcode)) {
                        ll_qrCode.visibility = View.VISIBLE
                    }
                    ll_handle.visibility = View.VISIBLE
                    ref_layout.setEnableLoadmore(false)
                    listview.adapter = mStepAdapter
                    when (mDetailsDto!!.status) {
                        1 -> {//审核
                            ll_handle.visibility = View.GONE
                        }
                        2 -> {//不通过
                            ll_handle.visibility = View.VISIBLE
                        }
                        3 -> {//暂停
                            ll_handle.visibility = View.VISIBLE
                        }
                        4 -> {//冻结
                            ll_handle.visibility = View.GONE
                        }
                        else -> {//进行中或者已结束
                            ll_handle.visibility = View.VISIBLE
                        }
                    }
                } else if (position == 1) {
                    if (mCommentList.size == 0) {
                        xloading_view.showEmpty()
                    } else {
                        xloading_view.showContent()
                    }
                    ll_qrCode.visibility = View.GONE
                    iv_taskQRCode.visibility = View.GONE
                    tv_linkText.visibility = View.GONE
                    ll_handle.visibility = View.GONE
                    listview.adapter = mCommentAdapter
                }
            }

            override fun onTabReselect(position: Int) {}
        })
        scrollView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            if (scrollY <= 0) {
                rl_title.setBackgroundColor(Color.argb(0, 250, 192, 52))
                tv_title.visibility = View.INVISIBLE
            } else if (scrollY > 0 && scrollY <= rl_title.height) {
                tv_title.visibility = View.VISIBLE
                val scale = scrollY.toFloat() / rl_title.height
                val alpha = 255 * scale
                // 只是layout背景透明(仿知乎滑动效果)
                rl_title.setBackgroundColor(Color.argb(alpha.toInt(), 250, 192, 52))
            } else {
                tv_title.visibility = View.VISIBLE
                rl_title.setBackgroundColor(Color.argb(255, 250, 192, 52))
            }
        })
        ref_layout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                super.onLoadMore(refreshLayout)
                pageNum++
                presenter.loadComment(missionId, pageNum)
            }
        })
        iv_back.setOnClickListener { finish() }
        tv_right.setOnClickListener { SubmitListActivity.open(mContext, missionId) }
        btn_handle_1.setOnClickListener {
            val countDown = mDetailsDto!!.endTimeStamp - Date().time / 1000
            if (countDown > 0) {//如果结束时间大于当前时间，就证明在进行中
                val hintDialog = HintDialog(mContext, "提示", "您确定提前结束此任务吗？", arrayOf("取消", "确定"))
                hintDialog.setCallback(object : HintDialog.Callback {
                    override fun callback() {
                        presenter!!.endTask(missionId)
                    }

                    override fun cancle() {}
                })
                hintDialog.show()
            } else {//否则就已经结束
                var hint = if(mDetailsDto!!.status == 2){
                    "确定删除该任务？"
                }else{
                    "删除任务后，用户提示的信息将被清除，确定删除该任务？"
                }
                val hintDialog = HintDialog(mContext, "提示", hint, arrayOf("取消", "确定"))
                hintDialog.setCallback(object : HintDialog.Callback {
                    override fun callback() {
                        presenter!!.deleteTask(missionId)
                    }

                    override fun cancle() {}
                })
                hintDialog.show()
            }
        }
        btn_handle_2.setOnClickListener {
            val countDown = mDetailsDto!!.endTimeStamp - Date().time / 1000
            if (countDown > 0) {//如果结束时间大于当前时间，就证明在进行中
                val hintDialog = HintDialog(mContext, "提示", "您确定暂停此任务吗？", arrayOf("取消", "确定"))
                hintDialog.setCallback(object : HintDialog.Callback {
                    override fun callback() {
                        presenter!!.suspendTask(missionId)
                    }

                    override fun cancle() {}
                })
                hintDialog.show()
            } else {//否则就已经结束
                presenter.loadTaskEditDetail(missionId)
            }
        }
        btn_handle_3.setOnClickListener {
            when (mDetailsDto!!.status) {
                2 -> {
                    presenter.loadTaskEditDetail(missionId)
                }
                3 -> {
                    if (handlerDialog == null) {
                        handlerDialog = HandlerDialog(mContext)
                    }
                    handlerDialog!!.setListenter(object : HandlerDialog.onClickListenter {
                        override fun onClickCommit(handlerType: Int) {
                            when (handlerType) {
                                1 -> {
                                    val hintDialog = HintDialog(mContext, "提示", "您确定开启此任务吗？", arrayOf("取消", "确定"))
                                    hintDialog.setCallback(object : HintDialog.Callback {
                                        override fun callback() {
                                            presenter!!.startTask(missionId)
                                        }

                                        override fun cancle() {}
                                    })
                                    hintDialog.show()
                                }
                                2 -> {
                                    if (priceDialog == null) {
                                        priceDialog = IncreasePriceDialog(mContext)
                                    }
                                    priceDialog!!.setData(mDetailsDto!!.img, mDetailsDto!!.title, mDetailsDto!!.beforeUnitPrice)
                                    priceDialog!!.setListenter(object : IncreasePriceDialog.onClickListenter {
                                        override fun onClickCommit(price: String) {
                                            IncreasePayActivity.open(mContext, mDetailsDto!!.id, (BigDecimal(price).subtract(mDetailsDto!!.beforeUnitPrice)).multiply(BigDecimal(mDetailsDto!!.surplusNum)).stripTrailingZeros().toPlainString(), price, IncreasePayActivity.INCREASE_PRICE)
                                            priceDialog = null
                                        }
                                    })
                                    priceDialog!!.show()
                                }
                                3 -> {
                                    if (numberDialog == null) {
                                        numberDialog = IncreaseNumberDialog(mContext)
                                    }
                                    numberDialog!!.setData(mDetailsDto!!.img, mDetailsDto!!.title, mDetailsDto!!.surplusNum)
                                    numberDialog!!.setListenter(object : IncreaseNumberDialog.onClickListenter {
                                        override fun onClickCommit(number: String) {
                                            IncreasePayActivity.open(mContext, mDetailsDto!!.id, mDetailsDto!!.beforeUnitPrice.multiply(BigDecimal(number)).stripTrailingZeros().toPlainString(), number.toInt(), IncreasePayActivity.INCREASE_NUMBER)
                                            numberDialog = null
                                        }
                                    })
                                    numberDialog!!.show()
                                }
                                4 -> {
                                    val hintDialog = HintDialog(mContext, "提示", "您确定提前结束此任务吗？", arrayOf("取消", "确定"))
                                    hintDialog.setCallback(object : HintDialog.Callback {
                                        override fun callback() {
                                            presenter!!.endTask(missionId)
                                        }

                                        override fun cancle() {}
                                    })
                                    hintDialog.show()
                                }
                            }
                        }
                    })
                    handlerDialog!!.show()
                }
            }
        }
        mCommentAdapter!!.setListener {
            if (!replyDialog.isShowing) {
                replyDialog.replyPosition(it)
                replyDialog.show()
            }
        }
        replyDialog.setListenter(object : ReplyDialog.onClickListenter {
            override fun onClickCommit(content: String, position: Int) {
                presenter.repleyComment(mCommentList[position].id, content, position)
            }
        })
    }

    override fun replySuccess(params: HashMap<String, Any>) {
        showToast("回复成功")
        mCommentList[params["position"] as Int].replyContent = params["replyContent"] as String
        mCommentAdapter!!.notifyDataSetChanged()
    }

    override fun showTaskDetails(result: ShopTaskDetailDto) {
        mDetailsDto = result
        val countDown = result.endTimeStamp - Date().time / 1000
        if (countDown < 0) {//如果结束时间小于当前时间，就证明已经结束了
            btn_handle_1.text = "删除"
            btn_handle_2.text = "重新发布"
            tv_task_status.visibility = View.GONE
            tv_task_status.text = ""
            tv_task_status.setBackgroundResource(R.drawable.draw_card_bg)
            ll_handle.visibility = View.VISIBLE
            btn_handle_1.visibility = View.VISIBLE
            btn_handle_2.visibility = View.VISIBLE
            btn_handle_3.visibility = View.GONE
        } else {//否则就是还没结束
            when (result.status) {
                1 -> {//审核
                    tv_task_status.visibility = View.VISIBLE
                    tv_task_status.setBackgroundResource(R.drawable.draw_card_status)
                    tv_task_status.text = "平台正在审核中，请耐心等待！"
                    ll_handle.visibility = View.GONE
                }
                2 -> {//不通过
                    tv_task_status.visibility = View.VISIBLE
                    tv_task_status.setBackgroundResource(R.drawable.draw_card_status)
                    tv_task_status.text = "该任务审核不通过！理由：" + result.refuseReason
                    ll_handle.visibility = View.VISIBLE
                    btn_handle_1.visibility = View.GONE
                    btn_handle_2.visibility = View.GONE
                    btn_handle_3.visibility = View.VISIBLE
                    btn_handle_3.text = "重新编辑"
                }
                3 -> {//暂停
                    tv_task_status.visibility = View.GONE
                    ll_handle.visibility = View.VISIBLE
                    btn_handle_1.visibility = View.GONE
                    btn_handle_2.visibility = View.GONE
                    btn_handle_3.visibility = View.VISIBLE
                    btn_handle_3.text = "管理"
                }
                4 -> {//冻结
                    tv_task_status.visibility = View.VISIBLE
                    tv_task_status.text = "改任务已被冻结!理由：" + result.frozenCause
                    tv_task_status.setBackgroundResource(R.drawable.draw_card_status)
                    ll_handle.visibility = View.GONE
                }
                else -> {//进行中或者已结束
                    tv_task_status.visibility = View.GONE
                    tv_task_status.text = ""
                    tv_task_status.setBackgroundResource(R.drawable.draw_card_bg)
                    ll_handle.visibility = View.VISIBLE
                    btn_handle_1.visibility = View.VISIBLE
                    btn_handle_2.visibility = View.VISIBLE
                    btn_handle_3.visibility = View.GONE
                    btn_handle_1.text = "结束任务"
                    btn_handle_2.text = "暂停任务"
                }
            }
        }
        imageUrl.addAll(listOf(*result.img.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()))
        bannerlayout.setImages(imageUrl)
        bannerlayout.start()
        tv_content_title.text = result.title
        tv_price.text = "￥" + result.unitPrice.stripTrailingZeros().toPlainString()
        tv_times.text = result.surplusNum.toString()
        tv_over.text = result.endTimeStr
        tv_cate.text = result.classificationName
        tv_authTime.text = result.auditHour.toString() + "小时内审核"
        when {
            result.deviceType == 1 -> tv_device.text = "全部"
            result.deviceType == 2 -> tv_device.text = "IOS"
            result.deviceType == 3 -> tv_device.text = "Android"
        }
        stepList.addAll(result.missionStepDtos)
        mStepAdapter!!.notifyDataSetChanged()
        if (!CheckUtil.isNull(result.missionQrcode)) {
            GlideUtil.loadPicture(result.missionQrcode, iv_taskQRCode, R.drawable.default_image)
            iv_taskQRCode.visibility = View.VISIBLE
        } else {
            iv_taskQRCode.visibility = View.GONE
        }
        if (!CheckUtil.isNull(result.missionUrl)) {
            tv_linkText.visibility = View.VISIBLE
            tv_linkText.text = result.missionUrl
        } else {
            tv_linkText.visibility = View.GONE
        }
        if (!CheckUtil.isNull(result.missionUrl) || !CheckUtil.isNull(result.missionQrcode)) {
            ll_qrCode.visibility = View.VISIBLE
        } else {
            ll_qrCode.visibility = View.GONE
        }
        if (openType == COMMENT_OPEN) {
            ll_qrCode.visibility = View.GONE
            iv_taskQRCode.visibility = View.GONE
            tv_linkText.visibility = View.GONE
            ll_handle.visibility = View.GONE
        }
    }

    override fun deleteSuccess() {
        showToast("删除成功")
        sendBroadcast(Intent("UPDATE_TASK_LIST"))
        finish()
    }

    override fun suspendSuccess() {
        showToast("任务已暂停")
        sendBroadcast(Intent("UPDATE_TASK_LIST"))
        presenter.loadTaskDetail(missionId)
    }

    override fun startSuccess() {
        showToast("任务已开启")
        sendBroadcast(Intent("UPDATE_TASK_LIST"))
        presenter.loadTaskDetail(missionId)
    }

    override fun endSuccess() {
        showToast("任务已结束")
        sendBroadcast(Intent("UPDATE_TASK_LIST"))
        presenter.loadTaskDetail(missionId)
    }

    override fun showEditDetail(editTaskDto: EditTaskDto) {
        ReleaseTaskActivity.open(mContext, editTaskDto)
    }

    override fun showTaskCommentList(result: List<TaskCommentDto>, pageNum: Int) {
        if (pageNum == 1) {
            mCommentList.clear()
        }
        mCommentList.addAll(result)
        mCommentAdapter!!.notifyDataSetChanged()

        if (mCommentList.size == 0&&openType == COMMENT_OPEN) {
            xloading_view.showEmpty()
        }else{
            xloading_view.showContent()
        }
        onLoad (result.size)
    }

    override fun showProLoading() {
        showLoading()
    }

    override fun dimissProLoading() {
        dismissLoading()
    }

    override fun showErrorMessage(postCode: Int, code: String, message: String) {
        showErrorMsg(code, message)
        onLoad(-1)
    }

    fun onLoad(size: Int) {
        if (ref_layout == null) {
            return
        }
        ref_layout.finishRefreshLoadingMore()
        if (size < 10) {
            ref_layout.enableLoadMore(false)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(myReceiver)
    }

    inner class MyReciver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent!!.action == "UPDATE_TASK_DETAIL") {
                presenter.loadTaskDetail(missionId)
            }
        }
    }

    override fun isUseBaseTitleBar(): Boolean {
        return false
    }

    override fun getViewId(): Int {
        return R.layout.activity_shop_taskdetail
    }

    companion object {
        const val NORAL_OPEN = 1001
        const val COMMENT_OPEN = 1002
        fun open(mContext: MBaseActivity<*>, missionId: Long, openType: Int) {
            val bundle = Bundle()
            bundle.putLong("missionId", missionId)
            bundle.putInt("openType", openType)
            mContext.startActivity(bundle, STaskDetailActivity::class.java)
        }
    }

    override fun onGetBundle(bundle: Bundle) {
        missionId = bundle.getLong("missionId")
        openType = bundle.getInt("openType")
    }
}
